const cookieparser = process.server ? require('cookieparser') : undefined

export const state = () => {
    return {
        user: null
    }
}

export const mutations = {
    setUser(state, data) {
        state.user = data
    }
}

export const actions = {
    // nuxtServerInit是特殊的action，会在服务端渲染期间自动调用
    nuxtServerInit({ commit }, { req }) {
        let user = null
        if (req && req.headers.cookie) {
            const parsedCookie = cookieparser.parse(req.headers.cookie)
            try {
                user = JSON.parse(parsedCookie.user)
            } catch (err) {
                // No valid cookie found
            }
        }
        commit('setUser', user)
    }
}